<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输手机号码"
            class="input-with-select"
            v-model="params.phone"
            clearable
            @clear="getUserPageList()"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUserPageList()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="showDialog()">添加用户</el-button>
        </el-col>
      </el-row>

      <el-table :data="userList" stripe style="width: 100%" border>
        <el-table-column prop="id" label="编号"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="password" label="密码"></el-table-column>
        <el-table-column prop="nikeName" label="昵称"></el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <el-switch
              active-value="1"
              inactive-value="2"
              v-model="scope.row.status"
              @change="changeUserStatus(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="日期"></el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              content="查询详情"
              placement="top"
              :enterable="false"
            >
              <el-button icon="el-icon-search" circle size="mini"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="修改" placement="top" :enterable="false">
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                size="mini"
                @click="showDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                size="mini"
                @click="deleteUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button type="primary" icon="el-icon-setting" circle size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.current"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="params.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <el-dialog
      :title="dailogTitle"
      :visible.sync="addUserDialogVisible"
      width="40%"
      :before-close="handleClose"
      @close="addUserDialogClose"
    >
      <el-form
        :model="addUserForm"
        :rules="addUserFormRules"
        ref="addUserFormRef"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username" >
          <el-input
            v-model="addUserForm.username"
           :disabled="usernameDisabled"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password" type="password" :disabled="passwordDisabled"></el-input>
        </el-form-item>

        <el-form-item label="昵称" prop="nikeName">
          <el-input v-model="addUserForm.nikeName"></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addUserForm.phone"></el-input>
        </el-form-item>

        <el-form-item label="启用" prop="status">
          <el-switch active-value="1" inactive-value="2" v-model="addUserForm.status"></el-switch>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="handleDialog(addUserForm.id)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'user',
  created() {
    this.getUserPageList()
  },
  data() {
    // 自定义校验手机规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确手机号码格式'))
    }
    return {
      dailogTitle: '',
      params: {
        phone: '',
        current: 1,
        size: 5
      },
      userList: [],
      total: 0,
      usernameDisabled: false,
      passwordDisabled: false,
      addUserDialogVisible: false,
      addUserForm: {},
      addUserFormRules: {
        username: [
          { required: true, message: '请输用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        nikeName: [
          { required: true, message: '请输用户昵称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输用户手机号码', trigger: 'blur' },
          { max: 11, message: '长度 11 个字符', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async getUserPageList() {
      const { data: res } = await this.$http.get('/user/getUserPageList', {
        params: this.params
      })
      if (res.flag) {
        this.userList = res.data.records
        this.total = res.data.total
      } else {
        return this.$message.error('res.msg')
      }
    },
    handleSizeChange(size) {
      this.params.size = size
      this.getUserPageList()
    },
    handleCurrentChange(current) {
      this.params.current = current
      this.getUserPageList()
    },
    async changeUserStatus(user) {
      const { data: res } = await this.$http.put(
        '/user/updateUserStatus/' + user.id
      )
      if (!res.flag) {
        user.status = !user.status
        return this.$message.error(res.msg)
      }
      return this.$message.success(res.msg)
    },
    async showDialog(id) {
      if (id !== undefined) {
        this.dailogTitle = '修改用户'
        const { data: res } = await this.$http.get('/user/getUserDetail/' + id)
        this.addUserForm = res.data
        this.usernameDisabled = true
        this.passwordDisabled = true
      } else {
        this.dailogTitle = '添加用户'
        this.addUserForm = {}
      }
      this.addUserDialogVisible = true
    },
    async deleteUser(id) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const { data: res } = await this.$http.delete('/user/deleteUser/' + id)

      if (!res.flag) {
        return this.$message.error(res.msg)
      }
      this.getUserPageList()
      return this.$message.success(res.msg)
    },
    handleClose() {
      this.addUserDialogVisible = false
    },
    addUserDialogClose() {
      this.$refs.addUserFormRef.resetFields()
    },
    async handleDialog(id) {
      this.$refs.addUserFormRef.validate(async valid => {
        if (!valid) return
        let result
        if (id > 0) {
          console.log('id = ' + id)
          const { data: res } = await this.$http.put(
            '/user/updateUser',
            this.addUserForm
          )
          result = res
        } else {
          const { data: res } = await this.$http.post(
            '/user/addUser',
            this.addUserForm
          )
          result = res
        }
        if (!result.flag) return this.$message.error(result.msg)
        this.addUserDialogVisible = false
        this.getUserPageList()
        return this.$message.success(result.msg)
      })
    }
  }
}
</script>

<style lang="less" scoped>
</style>
